package com.um.psystem.service.mtService.impl;

import cn.hutool.core.util.StrUtil;
import com.um.psystem.entity.ExcelHeader;
import com.um.psystem.enums.ResponseEnum;
import com.um.psystem.mapper.platform.PublicMapper;
import com.um.psystem.model.vo.JsonResult;
import com.um.psystem.service.mtService.IAssetsStockinService;
import com.um.psystem.utils.EasyExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Auther: qy
 * @Date: 2020/8/22 - 11:24
 * @Description: com.um.psystem.service.mtService.impl
 * @version: 1.0
 */
@Service
public class AssetsStockinService implements IAssetsStockinService {

    @Autowired
    PublicMapper publicMapper;

    @Override
    public List<Map<String, Object>> getStockinList(Map map) {
        String type_dtl_no="";
        String sqltmp="";
        String stockin_man="";
        Map paramsMap = new HashMap();
        Integer page = Integer.parseInt((map.get("page")!=null?map.get("page").toString():"0"));
        Integer rows = Integer.parseInt((map.get("rows")!=null?map.get("rows").toString():"0"));
        if(StrUtil.isNotBlank(map.get("type_dtl_no")!=null?map.get("type_dtl_no").toString():null)){
            sqltmp+=" and a.type_dtl_id=(select type_dtl_id from ws_eng_assets_type_dtl where type_dtl_no=#{type_dtl_no})";
            type_dtl_no =map.get("type_dtl_no").toString().trim();
            paramsMap.put("type_dtl_no",type_dtl_no);
        }
        if(StrUtil.isNotBlank(map.get("operator")!=null?map.get("operator").toString():null)){
            sqltmp+=" and a.operator=#{stockin_man}";
            stockin_man =map.get("operator").toString().trim();
            paramsMap.put("stockin_man",stockin_man);
        }
        String  sql = " select count(*) as totals from ws_eng_assets_stockin_record a where 1=1 "+sqltmp;
        System.out.println("--------------------------------------");
        System.out.println("sql1:"+sql);
        paramsMap.put("sqlStr",sql);
        int totals=0;
        List<Map<String,Object>> list_count = publicMapper.getPublicItems(paramsMap);
        if(list_count.size()>0){
            totals = Integer.parseInt(list_count.get(0).get("totals").toString());
        }
        sql = " select c.type_main_name,b.type_dtl_name,b.type_dtl_no,b.k3_code,b.model,b.sizes," +
                "a.num,b.unit,b.supplier,a.remarks," +
                "a.operator,a.datetime,"+totals+ " as totals," +
                "a.appendix_flag,a.id,a.download_url " +
                "from ws_eng_assets_stockin_record a " +
                "join ws_eng_assets_type_dtl b on a.type_dtl_id=b.type_dtl_id " +
                "join ws_eng_assets_type_main c on b.type_main_id=c.type_main_id " +
                "where 1=1 "+sqltmp+" order by id desc";
        if(page!=0 && rows!=0){
            sql+= " limit #{startIndex},#{rows} ";
            paramsMap.put("startIndex",(page-1)*rows);
            paramsMap.put("rows",rows);
        }
        paramsMap.put("sqlStr",sql);
        System.out.println("--------------------------------------");
        System.out.println("sql2:"+sql);
        return publicMapper.getPublicItems(paramsMap);
    }

    @Override
    public List<Map<String,Object>> getMtInfo(Map map) {
        String sqltemp="WHERE 1=1";
        Map paramsMap = new HashMap();
        if (map.containsKey("typeDtlNo") && map.get("typeDtlNo")!=null)
        {
            sqltemp += " AND a.type_dtl_no =#{type_dtl_no}";
            paramsMap.put("type_dtl_no",map.get("typeDtlNo").toString());
        }
        if (map.containsKey("k3_code") && map.get("k3_code")!=null)
        {
            sqltemp += " AND a.k3_code =#{k3_code}";
            paramsMap.put("k3_code",map.get("k3_code").toString());
        }

        String sql = "SELECT" +
                " a.k3_code AS k3Code," +
                " a.type_dtl_no AS typeDtlNo," +
                " b.type_main_name AS typeMain," +
                " a.type_dtl_name AS mtName," +
                " a.model AS model," +
                " a.sizes AS sizes," +
                " a.unit AS unit,a.supplier," +
                " a.type_dtl_id " +
                " FROM" +
                " ws_eng_assets_type_dtl a" +
                " JOIN ws_eng_assets_type_main b ON a.type_main_id = b.type_main_id " + sqltemp;
        paramsMap.put("sqlStr",sql);
        return publicMapper.getPublicItems(paramsMap);
    }


    @Override
    public JsonResult addMtRecord(Map map) {
        Map paramsMap = new HashMap();
        String sql = "INSERT INTO ws_eng_assets_stockin_record" +
                " VALUES" +
                " (NULL, #{type_dtl_id}, #{num}, #{supplier}, #{remarks}," +
                " #{username},now(),#{appendix_flag},null)";
        paramsMap.put("isqlStr",sql);
        paramsMap.put("type_dtl_id",map.get("type_dtl_id"));
        paramsMap.put("num",Integer.parseInt((String) map.get("num")));
        paramsMap.put("supplier",map.get("supplier"));
        paramsMap.put("remarks",map.get("remarks"));
        paramsMap.put("username",map.get("operator"));
        paramsMap.put("appendix_flag","0");
       // paramsMap.put("datetime",new Date());
        return JsonResult.success(publicMapper.saveItems(paramsMap));
    }

    @Override
    public List<Map<String,Object>> getRecordInfo(Map map) {
        Map paramsMap = new HashMap();
        String id = (String) map.get("id");
        String sql = "SELECT" +
                " a.k3_code AS k3Code," +
                " a.type_dtl_no AS typeDtlNo," +
                " b.type_main_name AS typeMain," +
                " a.type_dtl_name AS mtName," +
                " a.model AS model," +
                " a.sizes AS sizes," +
                " a.unit AS unit,a.supplier," +
                " a.type_dtl_id,c.remarks,c.num," +
                " c.id,c.operator " +
                " FROM" +
                " ws_eng_assets_type_dtl a" +
                " JOIN ws_eng_assets_type_main b ON a.type_main_id = b.type_main_id " +
                " join ws_eng_assets_stockin_record c on c.type_dtl_id=a.type_dtl_id " +
                " WHERE" +
                " c.id=" + id;
        paramsMap.put("sqlStr",sql);
        return publicMapper.getPublicItems(paramsMap);
    }

    @Override
    public JsonResult<Integer> updateMtRecord(Map map) {
        Map paramsMap = new HashMap();
        String sql = "UPDATE ws_eng_assets_stockin_record" +
                " SET " +
                "num=#{num}, remarks=#{remarks} ,datetime=now(),type_dtl_id=#{type_dtl_id} " +
                " WHERE id=#{id} ";
        paramsMap.put("usqlStr",sql);
        paramsMap.put("id",map.get("id"));
        paramsMap.put("num",Integer.parseInt((String) map.get("num")));
        paramsMap.put("type_dtl_id",map.get("type_dtl_id"));
        paramsMap.put("remarks",map.get("remarks"));
        Integer updateNum = publicMapper.updateItems(paramsMap);
        return JsonResult.success(updateNum);
    }

    @Override
    public JsonResult<Integer> updateAppendixFlag(Map map,String url) {
        Map paramsMap = new HashMap();
        String sql = "update ws_eng_assets_stockin_record set appendix_flag='1',download_url=#{url} " +
                "where id=#{id}";
        paramsMap.put("usqlStr",sql);
        paramsMap.put("id",map.get("rowid").toString());
        paramsMap.put("url",url);
        Integer updateNum = publicMapper.updateItems(paramsMap);
        return JsonResult.success(updateNum);
    }

    @Override
    public JsonResult<Integer> deleMtRecord(Integer id) {
        Map paramsMap = new HashMap();
        String sql = "DELETE FROM ws_eng_assets_stockin_record" +
                " WHERE" +
                " ID=#{id}";
        paramsMap.put("dsqlStr",sql);
        paramsMap.put("id",id);
        Integer updateNum = publicMapper.delItems(paramsMap);
        return JsonResult.success(updateNum);
    }

    @Override
    public void exportStockData(HttpServletResponse response, Map map) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = null;
        try {
            fileName = URLEncoder.encode("物料入库详情表", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
        List<ExcelHeader> headerList = new ArrayList<>();
        headerList.add(new ExcelHeader("id", "ID"));
        headerList.add(new ExcelHeader("type_main_name", "类型"));
        headerList.add(new ExcelHeader("type_dtl_name", "物料名称"));
        headerList.add(new ExcelHeader("type_dtl_no", "物料编码"));
        headerList.add(new ExcelHeader("k3_code", "K3编码"));
        headerList.add(new ExcelHeader("model", "型号"));
        headerList.add(new ExcelHeader("sizes", "规格参数"));
        headerList.add(new ExcelHeader("num", "入库数量"));
        headerList.add(new ExcelHeader("unit", "单位"));
        headerList.add(new ExcelHeader("supplier", "供应商"));
        headerList.add(new ExcelHeader("remarks", "备注"));
        headerList.add(new ExcelHeader("operator", "入库人"));

        ExcelHeader dateBackHeader = new ExcelHeader("datetime", "入库时间");
        dateBackHeader.setDataType(ExcelHeader.DATE);
        dateBackHeader.setFormat("yyyy-MM-dd HH:mm:ss");
        headerList.add(dateBackHeader);

        List<Map<String, Object>> dataList = getStockinList(map);
        OutputStream excelOutputStream = EasyExcelUtils.exportDataToExcel(headerList, dataList);
        try {
            response.getOutputStream().write(((ByteArrayOutputStream) excelOutputStream).toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
